package com.lq.controller;

import com.lq.pojo.Document;
import com.lq.pojo.User;
import com.lq.service.DocumentService;
import com.lq.util.SystemLogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Controller
public class DocumentController {

    @Autowired
    private DocumentService documentService;

    @RequestMapping("/deleteDocument")
    public String deleteDocument(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int documentId = Integer.parseInt(req.getParameter("dId"));

//        String path = new DocumentDao().getDocumentPathByDocId(documentId);
//        //在数据库中保存的文件路径分隔符为 “\”，需要转为“/”
//        String realPath = path.replace("\\","/");
//        //从硬盘删除
//        new File(realPath).delete();

        //从数据库删除保存的文件路径
        documentService.deleteDocumentById(documentId);

        SystemLogUtil.deleteDocumentLog();

        return "/getDocument";
    }


    @RequestMapping("/getDocument")
    public String getDocument(HttpSession session, Model model) {

        //分页获取上传文件路径
        // 获取前五个文件路径
        User user = (User) session.getAttribute("user");

        List<Document> documentList = documentService.getAllDocumentByUserId(0, 5, user.getUserId());

        model.addAttribute("documentList", documentList);

        return "document";
    }

    @RequestMapping("/uploading")
    public String uploading(HttpSession session) {

//            File path = new File("D:\\Code\\idea\\TaleBlog\\web\\WEB-INF\\uploadFile");
//
//            Part file = req.getPart("file");
//
//            String filePath = path.getPath()+File.separator+file.getSubmittedFileName();
//
//        try {
//
//            file.write(filePath);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        //将上传文件的全路径保存在数据库
//            User user = (User) session.getAttribute("user");
//            documentService.saveFile(filePath, user.getUserId());
//
//            return "/getDocument";
//        }

        return null;
    }
}
